/**
 * 登录页面相关的主要逻辑
 */

/**
 * 只显示指定的内容区域
 * @param {string} sectionId - 要显示的区域ID
 */
function showOnlySection(sectionId) {
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.style.display = 'none';
    });

    const targetSection = document.getElementById(sectionId);
    if (targetSection) {
        targetSection.style.display = 'block';
    }
}

/**
 * 显示指定的登录方式
 * @param {string} type - 登录类型
 */
function showLoginType(type) {
    // 隐藏所有登录表单
    const forms = document.querySelectorAll('.login-form');
    forms.forEach(form => form.classList.remove('active'));

    // 显示对应的登录形式
    switch (type) {
        case '1': // WhatsApp登录
            document.getElementById('whatsapp-login').classList.add('active');
            break;
        case '2': // Facebook登录
            document.getElementById('facebook-login').classList.add('active');
            break;
        case '3': // 密码登录
            document.getElementById('password-login').classList.add('active');
            break;
        case '4': // 短信登录
            document.getElementById('sms-login').classList.add('active');
            break;
        default:
            document.getElementById('sms-login').classList.add('active');
    }
}

/**
 * 初始化页面
 */
function initializePage() {
    const urlParams = getUrlParams();
    
    // 根据URL参数显示对应的登录方式
    if (urlParams.type) {
        showLoginType(urlParams.type);
    }

    // 设置事件监听器
    setupEventListeners();
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    // 密码登录表单提交
    const passwordForm = document.getElementById('password-login-form');
    if (passwordForm) {
        passwordForm.addEventListener('submit', handlePasswordLogin);
    }

    // 短信登录表单提交
    const smsForm = document.getElementById('sms-login-form');
    if (smsForm) {
        smsForm.addEventListener('submit', handleSmsLogin);
    }

    // 注册表单提交
    const registerForm = document.getElementById('register-form');
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }

    // 忘记密码表单提交
    const forgotForm = document.getElementById('forgot-password-form');
    if (forgotForm) {
        forgotForm.addEventListener('submit', handleForgotPassword);
    }

    // 发送验证码按钮
    const sendCodeBtn = document.getElementById('send-code-btn');
    if (sendCodeBtn) {
        sendCodeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const phone = document.getElementById('sms-phone').value;
            sendVerificationCode(phone, 'sms', 'send-code-btn');
        });
    }

    // 注册页面发送验证码
    const sendRegisterCodeBtn = document.getElementById('send-register-code-btn');
    if (sendRegisterCodeBtn) {
        sendRegisterCodeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const phone = document.getElementById('register-phone').value;
            sendVerificationCode(phone, 'register', 'send-register-code-btn');
        });
    }

    // 忘记密码发送验证码
    const sendForgotCodeBtn = document.getElementById('send-forgot-code-btn');
    if (sendForgotCodeBtn) {
        sendForgotCodeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const phone = document.getElementById('forgot-phone').value;
            sendVerificationCode(phone, 'forgot', 'send-forgot-code-btn');
        });
    }

    // 导航按钮
    const showRegisterBtn = document.getElementById('show-register');
    if (showRegisterBtn) {
        showRegisterBtn.addEventListener('click', function() {
            showOnlySection('register-section');
        });
    }

    const showForgotBtn = document.getElementById('show-forgot');
    if (showForgotBtn) {
        showForgotBtn.addEventListener('click', function() {
            showOnlySection('forgot-password-section');
        });
    }

    const backToLoginBtns = document.querySelectorAll('.back-to-login');
    backToLoginBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            showOnlySection('login-section');
        });
    });

    // 登录方式切换按钮
    const switchToPasswordBtn = document.getElementById('switch-to-password');
    if (switchToPasswordBtn) {
        switchToPasswordBtn.addEventListener('click', function() {
            showLoginType('3');
        });
    }

    const switchToSmsBtn = document.getElementById('switch-to-sms');
    if (switchToSmsBtn) {
        switchToSmsBtn.addEventListener('click', function() {
            showLoginType('4');
        });
    }

    const switchToWhatsappBtn = document.getElementById('switch-to-whatsapp');
    if (switchToWhatsappBtn) {
        switchToWhatsappBtn.addEventListener('click', function() {
            showLoginType('1');
        });
    }

    const switchToFacebookBtn = document.getElementById('switch-to-facebook');
    if (switchToFacebookBtn) {
        switchToFacebookBtn.addEventListener('click', function() {
            showLoginType('2');
        });
    }
}

/**
 * 处理密码登录
 * @param {Event} e - 事件对象
 */
function handlePasswordLogin(e) {
    e.preventDefault();
    
    const phone = document.getElementById('password-phone').value;
    const password = document.getElementById('password').value;

    // 清除之前的状态
    clearAllStatus('password');

    // 基本验证
    if (!phone || !password) {
        showError('password', '请填写完整信息');
        return;
    }

    if (!validatePhone(phone)) {
        showError('password', '请输入有效的手机号码');
        return;
    }

    if (!validatePassword(password)) {
        showError('password', '密码至少6位');
        return;
    }

    // 显示加载状态
    showLoading('password', true);

    // 发送登录请求
    fetchAPI('/api/password-login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            phone: phone,
            password: password
        })
    })
    .then(data => {
        showLoading('password', false);
        if (data.code === 200 || data.success) {
            showSuccess('password', '登录成功');
            // 处理登录成功回调
            if (data.token) {
                handleLoginSuccess(data.token);
            }
        } else {
            showError('password', data.message || '登录失败');
        }
    })
    .catch(error => {
        showLoading('password', false);
        handleAPIError(error, 'password');
    });
}

/**
 * 处理短信登录
 * @param {Event} e - 事件对象
 */
function handleSmsLogin(e) {
    e.preventDefault();
    
    const phone = document.getElementById('sms-phone').value;
    const code = document.getElementById('sms-code').value;

    // 清除之前的状态
    clearAllStatus('sms');

    // 基本验证
    if (!phone || !code) {
        showError('sms', '请填写完整信息');
        return;
    }

    if (!validatePhone(phone)) {
        showError('sms', '请输入有效的手机号码');
        return;
    }

    if (!validateCode(code)) {
        showError('sms', '请输入6位验证码');
        return;
    }

    // 显示加载状态
    showLoading('sms', true);

    // 发送登录请求
    fetchAPI('/api/sms-login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            phone: phone,
            code: code
        })
    })
    .then(data => {
        showLoading('sms', false);
        if (data.code === 200 || data.success) {
            showSuccess('sms', '登录成功');
            // 处理登录成功回调
            if (data.token) {
                handleLoginSuccess(data.token);
            }
        } else {
            showError('sms', data.message || '登录失败');
        }
    })
    .catch(error => {
        showLoading('sms', false);
        handleAPIError(error, 'sms');
    });
}

/**
 * 处理用户注册
 * @param {Event} e - 事件对象
 */
function handleRegister(e) {
    e.preventDefault();
    
    const phone = document.getElementById('register-phone').value;
    const password = document.getElementById('register-password').value;
    const confirmPassword = document.getElementById('register-confirm-password').value;
    const code = document.getElementById('register-code').value;

    // 清除之前的状态
    clearAllStatus('register');

    // 基本验证
    if (!phone || !password || !confirmPassword || !code) {
        showError('register', '请填写完整信息');
        return;
    }

    if (!validatePhone(phone)) {
        showError('register', '请输入有效的手机号码');
        return;
    }

    if (!validatePassword(password)) {
        showError('register', '密码至少6位');
        return;
    }

    if (!validatePasswordMatch(password, confirmPassword)) {
        showError('register', '两次密码输入不一致');
        return;
    }

    if (!validateCode(code)) {
        showError('register', '请输入6位验证码');
        return;
    }

    // 显示加载状态
    showLoading('register', true);

    // 发送注册请求
    fetchAPI('/api/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            phone: phone,
            password: password,
            code: code
        })
    })
    .then(data => {
        showLoading('register', false);
        if (data.code === 200 || data.success) {
            showSuccess('register', '注册成功，正在登录...');
            // 注册成功后自动登录
            setTimeout(() => {
                if (data.token) {
                    handleLoginSuccess(data.token);
                } else {
                    // 如果没有返回token，跳转到登录页面
                    showOnlySection('login-section');
                    showLoginType('3'); // 默认显示密码登录
                }
            }, 1500);
        } else {
            showError('register', data.message || '注册失败');
        }
    })
    .catch(error => {
        showLoading('register', false);
        handleAPIError(error, 'register');
    });
}

/**
 * 处理忘记密码
 * @param {Event} e - 事件对象
 */
function handleForgotPassword(e) {
    e.preventDefault();
    
    const phone = document.getElementById('forgot-phone').value;
    const newPassword = document.getElementById('forgot-new-password').value;
    const confirmPassword = document.getElementById('forgot-confirm-password').value;
    const code = document.getElementById('forgot-code').value;

    // 清除之前的状态
    clearAllStatus('forgot');

    // 基本验证
    if (!phone || !newPassword || !confirmPassword || !code) {
        showError('forgot', '请填写完整信息');
        return;
    }

    if (!validatePhone(phone)) {
        showError('forgot', '请输入有效的手机号码');
        return;
    }

    if (!validatePassword(newPassword)) {
        showError('forgot', '密码至少6位');
        return;
    }

    if (!validatePasswordMatch(newPassword, confirmPassword)) {
        showError('forgot', '两次密码输入不一致');
        return;
    }

    if (!validateCode(code)) {
        showError('forgot', '请输入6位验证码');
        return;
    }

    // 显示加载状态
    showLoading('forgot', true);

    // 发送重置密码请求
    fetchAPI('/api/reset-password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            phone: phone,
            newPassword: newPassword,
            code: code
        })
    })
    .then(data => {
        showLoading('forgot', false);
        if (data.code === 200 || data.success) {
            showSuccess('forgot', '密码重置成功，请使用新密码登录');
            // 重置成功后跳转到登录页面
            setTimeout(() => {
                showOnlySection('login-section');
                showLoginType('3'); // 显示密码登录
                // 可以预填手机号
                const passwordPhoneInput = document.getElementById('password-phone');
                if (passwordPhoneInput) {
                    passwordPhoneInput.value = phone;
                }
            }, 1500);
        } else {
            showError('forgot', data.message || '密码重置失败');
        }
    })
    .catch(error => {
        showLoading('forgot', false);
        handleAPIError(error, 'forgot');
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initializePage);
